package org.jeecg.modules.mes.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Date;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.entity.MesEmployeePieceWage;
import org.jeecg.modules.mes.service.IMesEmployeePieceWageService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * @Description: 员工计件工资记录表
 * @Author: jeecg-boot
 * @Date: 2025-01-01
 * @Version: V1.0
 */
@Api(tags="员工计件工资记录表")
@RestController
@RequestMapping("/mes/employeePieceWage")
@Slf4j
public class MesEmployeePieceWageController extends JeecgController<MesEmployeePieceWage, IMesEmployeePieceWageService> {
	@Autowired
	private IMesEmployeePieceWageService employeePieceWageService;
	
	/**
	 * 分页列表查询
	 *
	 * @param employeePieceWage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-分页列表查询")
	@ApiOperation(value="员工计件工资记录表-分页列表查询", notes="员工计件工资记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MesEmployeePieceWage employeePieceWage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesEmployeePieceWage> queryWrapper = QueryGenerator.initQueryWrapper(employeePieceWage, req.getParameterMap());
		Page<MesEmployeePieceWage> page = new Page<MesEmployeePieceWage>(pageNo, pageSize);
		IPage<MesEmployeePieceWage> pageList = employeePieceWageService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 计算计件工资
	 *
	 * @param taskId
	 * @param employeeId
	 * @param completedQuantity
	 * @param qualityScore
	 * @param efficiencyScore
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-计算工资")
	@ApiOperation(value="员工计件工资记录表-计算工资", notes="员工计件工资记录表-计算工资")
	@PostMapping(value = "/calculate")
	public Result<?> calculateWage(@RequestParam(name="taskId",required=true) String taskId,
								   @RequestParam(name="employeeId",required=true) String employeeId,
								   @RequestParam(name="completedQuantity",required=true) Integer completedQuantity,
								   @RequestParam(name="qualityScore",required=false) BigDecimal qualityScore,
								   @RequestParam(name="efficiencyScore",required=false) BigDecimal efficiencyScore) {
		try {
			MesEmployeePieceWage wageRecord = employeePieceWageService.calculatePieceWageWithBonus(
				taskId, employeeId, completedQuantity, qualityScore, efficiencyScore);
			
			if (wageRecord != null) {
				return Result.OK(wageRecord);
			} else {
				return Result.error("计算工资失败，请检查任务信息和计件标准配置！");
			}
		} catch (Exception e) {
			log.error("计算工资异常", e);
			return Result.error("计算工资异常：" + e.getMessage());
		}
	}
	
	/**
	 * 获取员工工资统计
	 *
	 * @param employeeId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-工资统计")
	@ApiOperation(value="员工计件工资记录表-工资统计", notes="员工计件工资记录表-工资统计")
	@GetMapping(value = "/employeeStats")
	public Result<?> getEmployeeWageStats(@RequestParam(name="employeeId",required=true) String employeeId,
										  @RequestParam(name="startDate",required=false) @DateTimeFormat(pattern="yyyy-MM-dd") Date startDate,
										  @RequestParam(name="endDate",required=false) @DateTimeFormat(pattern="yyyy-MM-dd") Date endDate) {
		List<MesEmployeePieceWage> wageStats = employeePieceWageService.getEmployeeWageStats(employeeId, startDate, endDate);
		return Result.OK(wageStats);
	}

	/**
	 * 获取员工日工资统计
	 *
	 * @param employeeId
	 * @param workDate
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-日工资统计")
	@ApiOperation(value="员工计件工资记录表-日工资统计", notes="员工计件工资记录表-日工资统计")
	@GetMapping(value = "/dailyWage")
	public Result<?> getDailyWage(@RequestParam(name="employeeId",required=true) String employeeId,
								  @RequestParam(name="workDate",required=true) @DateTimeFormat(pattern="yyyy-MM-dd") Date workDate) {
		List<MesEmployeePieceWage> dailyWage = employeePieceWageService.getDailyWageByEmployee(employeeId, workDate);
		return Result.OK(dailyWage);
	}

	/**
	 * 获取任务工资记录
	 *
	 * @param taskId
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-任务工资记录")
	@ApiOperation(value="员工计件工资记录表-任务工资记录", notes="员工计件工资记录表-任务工资记录")
	@GetMapping(value = "/taskWage")
	public Result<?> getTaskWage(@RequestParam(name="taskId",required=true) String taskId) {
		List<MesEmployeePieceWage> taskWage = employeePieceWageService.getWageRecordsByTask(taskId);
		return Result.OK(taskWage);
	}

	/**
	 * 获取待结算工资
	 *
	 * @param employeeId
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-待结算工资")
	@ApiOperation(value="员工计件工资记录表-待结算工资", notes="员工计件工资记录表-待结算工资")
	@GetMapping(value = "/pendingSettlement")
	public Result<?> getPendingSettlement(@RequestParam(name="employeeId",required=false) String employeeId) {
		List<MesEmployeePieceWage> pendingWages = employeePieceWageService.getPendingSettlementWages(employeeId);
		return Result.OK(pendingWages);
	}

	/**
	 * 批量结算工资
	 *
	 * @param wageIds
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-批量结算")
	@ApiOperation(value="员工计件工资记录表-批量结算", notes="员工计件工资记录表-批量结算")
	@PostMapping(value = "/batchSettle")
	public Result<?> batchSettle(@RequestParam(name="wageIds",required=true) String wageIds) {
		List<String> idList = Arrays.asList(wageIds.split(","));
		boolean result = employeePieceWageService.batchSettleWages(idList);
		
		if (result) {
			return Result.OK("批量结算成功！");
		} else {
			return Result.error("批量结算失败！");
		}
	}

	/**
	 * 获取员工工资统计信息
	 *
	 * @param employeeId
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-工资统计信息")
	@ApiOperation(value="员工计件工资记录表-工资统计信息", notes="员工计件工资记录表-工资统计信息")
	@GetMapping(value = "/stats")
	public Result<?> getWageStats(@RequestParam(name="employeeId",required=true) String employeeId) {
		try {
			// 获取员工当月工资统计
			BigDecimal monthlyWage = employeePieceWageService.getTotalWageByEmployee(employeeId, null, null);
			
			// 获取员工工资记录统计
			List<MesEmployeePieceWage> wageStats = employeePieceWageService.getEmployeeWageStats(employeeId, null, null);
			
			// 构建统计结果
			java.util.Map<String, Object> statsResult = new java.util.HashMap<>();
			statsResult.put("monthlyTotal", monthlyWage != null ? monthlyWage : BigDecimal.ZERO);
			statsResult.put("todayTotal", BigDecimal.ZERO); // 今日工资，可根据需要实现
			statsResult.put("weeklyTotal", BigDecimal.ZERO); // 本周工资，可根据需要实现
			statsResult.put("recordCount", wageStats != null ? wageStats.size() : 0);
			
			return Result.OK(statsResult);
		} catch (Exception e) {
			log.error("获取员工工资统计失败", e);
			return Result.error("获取工资统计失败：" + e.getMessage());
		}
	}

	/**
	 * 获取员工工资汇总
	 *
	 * @param employeeId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-工资汇总")
	@ApiOperation(value="员工计件工资记录表-工资汇总", notes="员工计件工资记录表-工资汇总")
	@GetMapping(value = "/totalWage")
	public Result<?> getTotalWage(@RequestParam(name="employeeId",required=true) String employeeId,
								  @RequestParam(name="startDate",required=false) @DateTimeFormat(pattern="yyyy-MM-dd") Date startDate,
								  @RequestParam(name="endDate",required=false) @DateTimeFormat(pattern="yyyy-MM-dd") Date endDate) {
		BigDecimal totalWage = employeePieceWageService.getTotalWageByEmployee(employeeId, startDate, endDate);
		return Result.OK(totalWage);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-通过id删除")
	@ApiOperation(value="员工计件工资记录表-通过id删除", notes="员工计件工资记录表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		employeePieceWageService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-批量删除")
	@ApiOperation(value="员工计件工资记录表-批量删除", notes="员工计件工资记录表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.employeePieceWageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "员工计件工资记录表-通过id查询")
	@ApiOperation(value="员工计件工资记录表-通过id查询", notes="员工计件工资记录表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MesEmployeePieceWage employeePieceWage = employeePieceWageService.getById(id);
		if(employeePieceWage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(employeePieceWage);
	}

    /**
     * 导出excel
     *
     * @param request
     * @param employeePieceWage
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesEmployeePieceWage employeePieceWage) {
        return super.exportXls(request, employeePieceWage, MesEmployeePieceWage.class, "员工计件工资记录表");
    }

}
